from django.shortcuts import render

# Create your views here.
from rest_framework import mixins, status
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from activities.models import Gathering
from activities.serializers.gathering import GatheringSerializer, GatheringDetailInfomationSerializer
from activities.utils import GatheringPageNumberClass
from users.models import User


class GatheringsView(ListAPIView):
    '''活动列表模块'''
    serializer_class = GatheringSerializer

    queryset = Gathering.objects.all()

    pagination_class = GatheringPageNumberClass


class GatheringDetailInfomationView(RetrieveAPIView):
    '''活动详情接口'''
    serializer_class = GatheringDetailInfomationSerializer

    queryset = Gathering.objects.all()

    pagination_class = None


class JoinGatheringsView(mixins.UpdateModelMixin,GenericViewSet):
    '''报名活动接口'''
    permission_classes = [IsAuthenticated]

    serializer_class = GatheringDetailInfomationSerializer

    queryset = Gathering.objects.all()

    def update(self, request, *args, **kwargs):

        partial = kwargs.pop('pk', False)

        instance = self.get_object()

        serializer = self.get_serializer(instance, data=request.data, partial=partial)

        serializer.is_valid(raise_exception=True)

        instance.users.add(User.objects.get(id=request.user.id))

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response({"id":partial,"message":"ok","success":True},status=status.HTTP_200_OK)




